package zhuzx.report;

import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zhuzx.util.*;

@Controller
@RequestMapping("/reportCtrl")
public class BackupReportCtrl {
	
	@RequestMapping(value = "/resolvePageData")
	public void resolvePageData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		byte[] bytes = GeneralUtil.getBytes(request.getInputStream());
		if ("Y".equals(request.getHeader("useGzip"))) {
			bytes = FileOperationUtil.gzipUnCompressToBytes(new ByteArrayInputStream(bytes));
		}
		String paramStr = new String(bytes, StandardCharsets.UTF_8);
//		System.out.println(paramStr.substring(1,100) + "\n……\n……\n" + paramStr.substring(paramStr.length()-100));
		String[] datas = MicroUtil.splitByStringAutoEscape(paramStr, TextConstants.HTTP_ENTITY_SEPARATOR);
		List<Map<String,String>> list = WebUtil.createListMapFromJsonArray(datas[0]);
		list = JavaScriptResolver.convertResultSet(list, datas[1], datas[3]);
		byte[] excelBytes = ExcelUtil.createExcel(true, null, null, list);
		//http://car.rsscc.com/cc/fmall/driverorder
		String fileName = JavaScriptResolver.getNameByUrl(datas[2]);
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + ".xlsx\"");
		OutputStream os = response.getOutputStream();
		os.write(excelBytes);
		os.close();
	}
	
	@ResponseBody
	@RequestMapping(value = "/receivePageData")
	public String receivePageData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String paramStr = new String(GeneralUtil.getBytes(request.getInputStream()), StandardCharsets.UTF_8);
		Map<String,String> headers = WebUtil.getHeaders(request);
		headers.put("bodyData", paramStr);
		return BackupReportProcessor.pushIntoQueue(headers);
	}
	
}